<template>
    <div>
        <el-button type="success" @click="AddUrlProduction">新增</el-button>
        <el-button type="success" @click="ExcelProduction" :loading="exportLoading">导出计划</el-button>
        <el-button type="primary" @click="showOperationRecordsDialog">操作记录</el-button>
        <!-- <el-button @click="handleImport">导入</el-button> -->
        <br>
        <br>
        <!-- 查询条件部分 -->
        <div class="search-section">
            <el-form :inline="true" :model="prolist">
                <el-form-item label="计划日期">
                    <el-date-picker
                        v-model="prolist.ScheduledDates"
                        type="date"
                        required
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="计划状态">
                    <el-select v-model="prolist.isload">
                        <el-option value="0">未执行</el-option>
                        <el-option value="1">执行中</el-option>
                        <el-option value="2">执行完毕</el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产量单位">
                    <el-input v-model="prolist.ProductionUnits"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button @click="GetProductionPlanning">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <span style="font-size: 20px; margin-left: 20px; font-weight: bold">计划列表</span>

        <input ref="fileInput" type="file" style="display: none" @change="handleFileChange" />
        <!-- 生产计划列表（仅展示序号列相关结构） -->
        <div class="table-container">
            <el-table :data="planList" stripe ref="tableRef" height="300">
                <el-table-column>
                    <template #header>
                        <el-checkbox v-model="allChecked" @change="handleCheckAllChange"></el-checkbox>
                    </template>
                    <template #default="scope">
                        <el-checkbox v-model="checkedIds" :value="scope.row.packagingPlanId"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column prop="packagingPlanId" label="主键"></el-table-column>
                <el-table-column prop="planType" label="计划类型">
                    <template #default="scope">
                        {{ scope.row.planType === 1? "包装计划" : scope.row.planType === 2? "过滤计划": scope.row.planType === 3? "生产计划" : "其他计划" }}
                    </template>
                </el-table-column>
                <el-table-column prop="scheduledDates" label="计划日期" width="130">
                    <template #default="scope">
                        {{ scope.row.scheduledDates? (new Date(scope.row.scheduledDates).getFullYear() + '年' + String(new Date(scope.row.scheduledDates).getMonth() + 1).padStart(2, '0') + '月' + String(new Date(scope.row.scheduledDates).getDate()).padStart(2, '0') + '日') : '' }}
                    </template>
                </el-table-column>
                <el-table-column prop="packingSpecifications" label="包装规格" width="120"></el-table-column>
                <el-table-column prop="packagingForm" label="包装形式" width="120"></el-table-column>
                <el-table-column prop="productRange" label="产品系列" width="120"></el-table-column>
                <el-table-column prop="plannedProduction" label="计划产量"></el-table-column>
                <el-table-column prop="productionUnits" label="产量单位"></el-table-column>
                <el-table-column prop="isload" label="执行状态">
                    <template #default="scope">
                        <span :style="{ color: getStatusColor(scope.row.isload) }" @click="handleStatusClick(scope.row.isload, scope.row.packagingPlanId)">
                            {{ scope.row.isload === 0? '未执行' : scope.row.isload === 1? '执行中' : '执行完毕' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="preparation" label="是否备料">
                    <template #default="scope">
                        <span :style="{ color: getStatusColor(scope.row.preparation? 2 : 0) } "  @click="handlepreparation(scope.row.preparation, scope.row.packagingPlanId)">
                            {{ scope.row.preparation === true? '已备料' : '未备料' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="picking" label="是否领料">
                    <template #default="scope">
                        <span :style="{ color: getStatusColor(scope.row.picking? 2 : 0) } ">
                            {{ scope.row.picking === true? '已领料' : '未领料' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="180"></el-table-column>
                <el-table-column prop="packagingPlanId" label="操作" fixed="right" width="180">
                    <template #default="scope">
                        <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.packagingPlanId)">编辑</el-button>
                        <el-button type="text" @click="DeleteProductionPlanning(scope.row.packagingPlanId)">删除</el-button>
                        <el-button type="text" @click="GetByProductionPlanning(scope.row.packagingPlanId)">详情</el-button>
                        <template v-if="!scope.row.preparation">
                            <el-button @click="GetPreparation(scope.row.packagingPlanId)">备料</el-button>
                        </template>
                        <template v-if="!scope.row.picking && scope.row.preparation">
                            <el-button @click="showMaterialInfo(scope.row.packagingPlanId)">领料</el-button>
                        </template>
                        <template v-if=" scope.row.picking">
                            <el-button @click="GetProductionPlanningDetail(scope.row.packagingPlanId)">接收计划</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <el-button @click="batchDelete">批量删除</el-button>
        </div>
        <!-- 分页部分 -->
        <div class="demo-pagination-block">
            <el-pagination
                v-model:current-page="page.PageIndex"
                v-model:page-size="page.PageSize"
                :page-sizes="[10, 20, 30, 50]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <!-- 备料弹出框 -->
        <el-dialog
            v-model="preparationDialogVisible"
            title="备料信息"
            width="60%"
            :before-close="handleClosePreparationDialog"
        >
            <el-table :data="preparationData" border>
                <el-table-column prop="ItemName" label="物料名称">
                    <template #default="{ row }">
                        <el-input v-model="row.ItemName"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="ItemSpecification" label="物料规格">
                    <template #default="{ row }">
                        <el-input v-model="row.ItemSpecification"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="ItemType" label="物料类型">
                    <template #default="{ row }">
                        <el-input v-model="row.ItemType"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="LotNumber" label="批次号">
                    <template #default="{ row }">
                        <el-input v-model="row.LotNumber"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="ManufactureDate" label="生产日期">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.ManufactureDate"
                            type="date"
                            @change="checkDateOrder(row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column prop="ExpirationDate" label="有效期">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.ExpirationDate"
                            type="date"
                            @change="checkDateOrder(row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column prop="PlannedQuantity" label="计划备料数量">
                    <template #default="{ row }">
                        <el-input v-model="row.PlannedQuantity" type="number"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="ActualQuantity" label="实际备料数量">
                    <template #default="{ row }">
                        <el-input v-model="row.ActualQuantity" type="number"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="Unit" label="单位">
                    <template #default="{ row }">
                        <el-input v-model="row.Unit"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button type="text" @click="deleteRow(row)" :disabled="row.isSaved">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button @click="addRow">新增行</el-button>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="preparationDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="savePreparation">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 查看备料信息弹出框 -->
        <el-dialog
            v-model="materialInfoDialogVisible"
            title="备料详细信息"
            width="60%"
        >
            <el-table :data="materialInfoData" border>
                <el-table-column prop="itemName" label="物料名称"></el-table-column>
                <el-table-column prop="itemspecification" label="物料规格"></el-table-column>
                <el-table-column prop="itemType" label="物料类型"></el-table-column>
                <el-table-column prop="lotNumber" label="批次号"></el-table-column>
                <el-table-column prop="manufactureDate" label="生产日期">
                    <template #default="{ row }">
                        {{ new Date(row.manufactureDate).getFullYear() + '年' + String(new Date(row.manufactureDate).getMonth() + 1).padStart(2, '0') + '月' + String(new Date(row.manufactureDate).getDate()).padStart(2, '0') + '日' }}
                    </template>
                </el-table-column>
                <el-table-column prop="expirationDate" label="有效期">
                    <template #default="{ row }">
                        {{ new Date(row.expirationDate).getFullYear() + '年' + String(new Date(row.expirationDate).getMonth() + 1).padStart(2, '0') + '月' + String(new Date(row.expirationDate).getDate()).padStart(2, '0') + '日' }}
                    </template>
                </el-table-column>
                <el-table-column prop="plannedQuantity" label="计划备料数量"></el-table-column>
                <el-table-column prop="actualQuantity" label="实际备料数量"></el-table-column>
                <el-table-column prop="unit" label="单位"></el-table-column>
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="materialInfoDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleMaterialInfoConfirm">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 操作记录弹出框 -->
        <el-dialog
            v-model="operationRecordsDialogVisible"
            title="操作记录"
        >
            <el-table :data="operationRecordsData" border style="margin-bottom: 20px;height: 300px;">
                <el-table-column prop="recordsOperationsId" label="操作编号" width="100"></el-table-column>
                <el-table-column prop="operatingTime" label="操作时间" width="180">
                    <template #default="scope">
                        {{ formatDate(scope.row.operatingTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="operator" label="操作人员" width="100"></el-table-column>
                <el-table-column prop="operationContent" label="操作内容" min-width="100"></el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-pagination
                v-model:current-page="operationPage.PageIndex"
                v-model:page-size="operationPage.PageSize"
                :page-sizes="[10, 20, 30, 50]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="operationTotal.totalCount"
                @size-change="handleOperationSizeChange"
                @current-change="handleOperationCurrentChange"
            />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import router from '@/router';

// 定义分页对象
const page = ref({
    PageIndex: 1,
    PageSize: 50,
});

// 定义搜索表单数据
const prolist = ref({
    ScheduledDates: '',
    ProductionUnits: '',
    isload: '',
});

// 定义分页总数
const total = ref({
    totalCount: 0,
    totalPage: 0,
});

// 模拟包装计划列表数据
const planList = ref([
    {
        "packagingPlanId": 0,
        "planType": 0,
        "scheduledDates": "",
        "packingSpecifications": "",
        "packagingForm": "",
        "productRange": "",
        "plannedProduction": '',
        "productionUnits": "",
        "materialRequirementsBill": "",
        "isload": 0,
        "preparation": false,
        Picking: false,
        "remark": ""
    }
]);

// 表格引用
const tableRef = ref(null);

// 全选状态
const allChecked = ref(false);
// 选中的 ID 列表
const checkedIds = ref([]);
//导出计划方法
const exportLoading = ref(false);

// 查询方法
const search = () => {
    console.log('查询条件：', prolist.value);
    // 这里可以添加实际的查询逻辑
    GetProductionPlanning();
};

const GetProductionPlanning = () => {
    axios.get('http://8.154.44.176:8000/p2-read/api/PackagingPlan/GetPackagingPlan', {
        params: {
            PageIndex: page.value.PageIndex,
            PageSize: page.value.PageSize,
            ScheduledDates: prolist.value.ScheduledDates,
            ProductionUnits: prolist.value.ProductionUnits,
            isload: prolist.value.isload
        }
    }).then((res) => {
        planList.value = res.data.data.list;
        total.value.totalCount = res.data.data.totalCount;
        total.value.totalPage = res.data.data.totalPage;
        // 重置全选状态和选中的 ID 列表
        allChecked.value = false;
        checkedIds.value = [];
    });
};

const handleSizeChange = (val) => {
    page.value.PageSize = val;
    GetProductionPlanning();
};
const handleCurrentChange = (val) => {
    page.value.PageIndex = val;
    GetProductionPlanning();
};

onMounted(() => {
    GetProductionPlanning();
});

//跳转编辑页面
const GetBYIdProductionPlanning = (packagingPlanId) => {
    router.push({
        name: 'GetBYIdPackagingPlanView',
        query: {
            packagingPlanId: packagingPlanId
        }
    });
    console.log(packagingPlanId);
};

//跳转编辑页面
const GetByProductionPlanning = (packagingPlanId) => {
    router.push({
        name: 'GetBYIddetailView',
        query: {
            packagingPlanId: packagingPlanId
        }
    });
    console.log(packagingPlanId);
};



// 删除单条记录
const DeleteProductionPlanning = async (packagingPlanId) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除该条记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await axios.post(
                `http://8.154.44.176:8000/p2-write/api/PackagingPlan/DelPackagingPlan`,
                {
                    packagingPlanIds: packagingPlanId.toString()
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('删除成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error!== 'cancel') {
            console.error('删除错误:', error);
            ElMessage.error('删除失败，请检查网络或联系管理员');
        }
    }
};

// 处理全选
const handleCheckAllChange = (value) => {
    if (value) {
        checkedIds.value = planList.value.map(item => item.packagingPlanId);
    } else {
        checkedIds.value = [];
    }
    allChecked.value = value;
};

// 批量删除
const batchDelete = async () => {
    if (checkedIds.value.length === 0) {
        ElMessage.warning('请选择要删除的记录');
        return;
    }
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除选中的记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const ids = checkedIds.value.join(',');
            const response = await axios.post(
                `http://8.154.44.176:8000/p2-write/api/PackagingPlan/DelPackagingPlan`,
                {
                    packagingPlanIds: ids
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('批量删除成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`批量删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error!== 'cancel') {
            console.error('批量删除错误:', error);
            ElMessage.error('批量删除失败，请检查网络或联系管理员');
        }
    }
};

  //导出Excel表
  const ExcelProduction = async () => {
    exportLoading.value = true;
    try {
      const response = await axios.get('http://8.154.44.176:8000/p2-read/api/PackagingPlan/ExportToExcel', {
        responseType: 'blob'
      });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'production_data.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      ElMessage.success('导出成功');
    } catch (error) {
      ElMessage.error('导出失败，请重试');
    } finally {
      exportLoading.value = false;
    }
  }

//跳转添加计划页面
const AddUrlProduction = () => {
    router.push({
        name: 'AddPackagingPlanView',
    });
}

//执行计划
const GetProductionPlanningDetail = async (packagingPlanId) => {
    try {
        // 先获取计划的详细信息，假设接口为 /api/PackagingPlan/GetPlanDetail
        const detailResponse = await axios.get(`http://8.154.44.176:8000/p2-read/api/PackagingPlan/GetBYIdPackagingPlan`, {
            params: {
                packagingPlanId: packagingPlanId
            }
        });

        const isload = detailResponse.data.data[0].isload;
        console.log('isload值:' + detailResponse.data.data[0].isload);

        if (isload === 1) {
            ElMessage.warning('计划正在执行中');
            return;
        }

        if (isload === 2) {
            ElMessage.warning('计划已经执行完毕');
            return;
        }

        const confirmResult = await ElMessageBox.confirm(
            '确认执行该计划吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await axios.post(
                `http://8.154.44.176:8000/p2-write/api/PackagingPlan/UpdatePackagingPlanStatus`,
                {
                    packagingPlanId: packagingPlanId
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('执行成功');
                GetProductionPlanning();

            } else {
                ElMessage.error(`执行失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error!== 'cancel') {
            console.error('执行错误:', error);
            ElMessage.error('执行失败，请检查网络或联系管理员');
        }
    }
};


//导入Excel表
const fileInput = ref(null);

const handleImport = () => {
    fileInput.value.click();
};

const handleFileChange = async (event) => {
    const files = event.target.files;
    if (files.length > 0) {
        const file = files[0];
        const formData = new FormData();
        formData.append('file', file); // 假设后端接口接收的文件参数名为 'file'

        try {
            const response = await axios.post('/z-write/api/Managerment/ImportExcel', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            console.log('导入成功:', response.data);
        } catch (error) {
            console.error('导入失败:', error);
        }
    }
    // 清空输入框，以便下次选择相同文件时也能触发 change 事件
    fileInput.value.value = '';
    GetProductionPlanning();
};

// 根据状态值获取颜色
const getStatusColor = (status) => {
    switch (status) {
        case 0:
            return 'gray'; // 未执行，灰色
        case 1:
            return 'orange'; // 执行中，橙色
        case 2:
            return 'green'; // 执行完毕，绿色
        default:
            return 'black';
    }
};

// 处理状态点击事件
const handleStatusClick = (status, packagingPlanId) => {
    switch (status) {
        case 0:
            ElMessage.warning('计划未被接收并执行');
            break;
        case 1:
            router.push({
                name: 'CreateReport', // 替换为实际的执行页面名称
                query: {
                    packagingPlanId: packagingPlanId
                }
            });
            break;
        case 2:
            ElMessage.success('计划已经执行完毕');
            break;
        default:
            break;
    }
};

// 处理是否备料点击事件
const handlepreparation = (status, packagingPlanId) => {
    materialInfoDialogVisible.value = true;
}

// 备料弹出框相关
const preparationDialogVisible = ref(false);
const preparationData = ref([]);
const currentPackagingPlanId = ref(null);

const GetPreparation = (packagingPlanId) => {
    currentPackagingPlanId.value = packagingPlanId;
    // 这里可以根据 packagingPlanId 去获取备料的初始数据，目前先清空
    preparationData.value = [];
    // 新增一行并绑定计划主键
    addRow();
    preparationDialogVisible.value = true;
};

const addRow = () => {
    preparationData.value.push({
        LotNumber: "",
        ItemType: "",
        ManufactureDate: "",
        ExpirationDate: "",
        Unit: "",
        PackagingPlanId: currentPackagingPlanId.value, // 绑定计划主键
        ItemName: '',
        ItemSpecification: '',
        PlannedQuantity: 0,
        ActualQuantity: 0
    });
};

const deleteRow = (row) => {
    ElMessageBox.confirm('确认删除该条明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = preparationData.value.indexOf(row);
        if (index !== -1) {
            preparationData.value.splice(index, 1);
            ElMessage.success('明细删除成功');
        }
    }).catch(() => {
        ElMessage.info('取消删除');
    });
};

const savePreparation = async () => {
    // 检查是否有数据
    if (preparationData.value.length === 0) {
        ElMessage.error('请添加备料数据');
        return;
    }
    const item = preparationData.value[0];

    // 检查必填项
    if (!item.ItemName ||!item.ItemSpecification ||!item.ItemType ||!item.LotNumber ||!item.ManufactureDate ||!item.ExpirationDate ||!item.PlannedQuantity ||!item.ActualQuantity ||!item.Unit) {
        ElMessage.error('请填写所有必填项');
        return;
    }

    // 构造符合 Swagger 格式的数据
    const dataToSend = {
        itemName: item.ItemName,
        itemspecification: item.ItemSpecification,
        itemType: item.ItemType,
        lotNumber: item.LotNumber,
        manufactureDate: new Date(item.ManufactureDate).toISOString(),
        expirationDate: new Date(item.ExpirationDate).toISOString(),
        plannedQuantity: Number(item.PlannedQuantity),
        actualQuantity: Number(item.ActualQuantity),
        unit: item.Unit,
        packagingPlanId: currentPackagingPlanId.value
    };

    try {
        const response = await axios.post(
            `http://8.154.44.176:8000/p2-write/api/MaterialPreparation/Handle`,
            dataToSend
        );
        if (response.data.code === 200) {
            ElMessage.success('备料数据保存成功');
            preparationDialogVisible.value = false;
            // 清空备料数据
            preparationData.value = [];
            GetProductionPlanning();

        } else {
            ElMessage.error(`备料数据保存失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('保存备料数据错误:', error);
        ElMessage.error('保存备料数据失败，请检查网络或联系管理员');
    }
};

const handleClosePreparationDialog = () => {
    // 关闭对话框时可以添加一些确认逻辑，这里简单直接关闭
    preparationDialogVisible.value = false;
};

// 日期验证函数
const checkDateOrder = (row) => {
    const { ManufactureDate, ExpirationDate } = row;
    if (ManufactureDate && ExpirationDate && new Date(ManufactureDate) > new Date(ExpirationDate)) {
        ElMessage.error('有效期不能小于生产日期');
        row.ExpirationDate = null;
    }
};

// 查看备料信息弹出框相关
const materialInfoDialogVisible = ref(false);
const materialInfoData = ref([]);
let currentViewPackagingPlanId = ref(null);

const showMaterialInfo = async (packagingPlanId) => {
    currentViewPackagingPlanId.value = packagingPlanId;
    try {
        const response = await axios.get(`http://8.154.44.176:8000/p2-read/api/PackagingPlan/GetByIdMaterialPreparation`, {
            params: {
                packagingPlanId: packagingPlanId
            }
        });
        materialInfoData.value = response.data.data;
        materialInfoDialogVisible.value = true;
    } catch (error) {
        console.error('获取备料信息失败:', error);
        ElMessage.error('获取备料信息失败，请检查网络或联系管理员');
    }
};

const handleMaterialInfoConfirm = async () => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认从物料表领料吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await axios.post(
                `http://8.154.44.176:8000/p2-write/api/PackagingPlan/UpdatePicking`,
                {
                    packagingPlanId: currentViewPackagingPlanId.value,
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('领料成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`领料失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error!== 'cancel') {
            console.error('领料错误:', error);
            ElMessage.error('领料失败，请检查网络或联系管理员');
        }
    }
    materialInfoDialogVisible.value = false;
};

// 操作记录分页参数
const operationPage = ref({
    PageIndex: 1,
    PageSize: 10
});

// 操作记录总数
const operationTotal = ref({
    totalCount: 0
});

// 操作记录数据
const operationRecordsData = ref([]);

// 操作记录对话框显示状态
const operationRecordsDialogVisible = ref(false);

// 打开操作记录对话框
const showOperationRecordsDialog = () => {
    operationPage.value.PageIndex = 1; // 重置为第一页
    getOperationRecords();
    operationRecordsDialogVisible.value = true;
};

// 获取操作记录数据
const getOperationRecords = async () => {
    try {
        const response = await axios.get('http://8.154.44.176:8000/p2-read/api/PackagingPlan/GetRecordsOperations', {
            params: {
                PageIndex: operationPage.value.PageIndex,
                PageSize: operationPage.value.PageSize
            }
        });

        if (response.data.code === 200) {
            operationRecordsData.value = response.data.data.list || [];
            operationTotal.value.totalCount = response.data.data.totalCount || 0;
        } else {
            ElMessage.error(`获取操作记录失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('操作记录请求错误:', error);
        ElMessage.error('获取操作记录失败，请检查网络连接');
    }
};

// 页大小改变处理
const handleOperationSizeChange = (size) => {
    operationPage.value.PageSize = size;
    getOperationRecords();
};

// 当前页改变处理
const handleOperationCurrentChange = (page) => {
    operationPage.value.PageIndex = page;
    getOperationRecords();
};

// 日期格式化函数
const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};    

// 操作类型文本转换
const getOperationTypeText = (type) => {
    const types = {
        1: '新增计划',
        2: '编辑计划',
        3: '删除计划',
        4: '执行计划',
        5: '备料操作',
        6: '领料操作'
    };
    return types[type] || '未知操作';
};
</script>

<style scoped>
.search-section {
    margin-bottom: 20px;
}

.table-container {
    max-height: 400px; /* 固定表格最大高度 */
    overflow-y: auto; /* 超出高度显示滚动条 */
    margin-bottom: 20px; /* 为分页预留空间 */
}

.el-table {
    width: 100%; /* 表格宽度占满容器 */
}

/* 操作记录表格样式 */
.el-dialog .el-table {
    width: 100%;
}

.el-dialog .el-pagination {
    margin-top: 20px;
    text-align: right;
}
</style>    